﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Imaging;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EMRI.EmergencyCare.Web.DataContext;
using EMRI.EmergencyCare.Web.Filters;
using EMRI.EmergencyCare.Web.Helper;
using EMRI.EmergencyCare.Web.Models;

namespace EMRI.EmergencyCare.Web.Controllers
{
    [InitializeSimpleMembership]
    public class PatientController : Controller
    {
        private readonly EmergencyManagementContext _db = new EmergencyManagementContext();

        //
        // GET: /PatientCare/
        public ActionResult Index()
        {
            var targetDateTime = DateTime.Today.AddDays(
                Convert.ToInt32(ConfigurationManager.AppSettings["RecentDaysOfRecordsToBeDisplayed"]) * -1);
            var location = SessionHelper.GetLocation(HttpContext);

            var patients = _db.Patients.Where(
                p => p.CreatedDate >= targetDateTime &&
                     string.IsNullOrEmpty(location) ||
                     (!string.IsNullOrEmpty(location) && p.Location.Equals(location, StringComparison.OrdinalIgnoreCase)))
                              .ToList();

            return View(patients.OrderByDescending(p => p.PatientId).Select(p => new PatietViewModel()
            {
                Patient = p,
                IsPatientDetailsAvailable = PatientHelper.IsPatientDetailsAvailable(p.PatientId, _db)
            }));
        }

        //Search patient name
        // GET: /PatientCare/
        public ActionResult Search(string searchText)
        {
            var patients = _db.Patients.Where(p => p.Name.StartsWith(searchText)).ToList();

            return View("Index", patients.OrderByDescending(p => p.PatientId).Select(p => new PatietViewModel()
                {
                    Patient = p,
                    IsPatientDetailsAvailable = PatientHelper.IsPatientDetailsAvailable(p.PatientId, _db)
                }));
        }

        //
        // GET: /PatientCare/Details/5
        public ActionResult Details(int patientId = 0)
        {
            var patient = _db.Patients.Find(patientId);
            var patientDetails = _db.PatientDetails.Include("InitialAssesment")
                                            .Include("DetailedAssesment.Readings")
                                            .Include("Investigation")
                                            .Include("Treatment.LifeLines")
                                            .Include("Treatment.TreatmentDetails")
                                            .Include("Synopsis")
                                            .SingleOrDefault(p => p.PatientId == patientId);
            if (patient == null || patientDetails == null)
            {
                return HttpNotFound();
            }
            ViewData["District"] = _db.Districts.Find(patientDetails.District).Name;
            ViewData["Taluk"] = _db.Taluks.Find(patientDetails.Taluk).Name;
            ViewData["City"] = _db.Cities.Find(patientDetails.City).Name;
            return View(new PatientDetailsViewModel() { Patient = patient, PatientDetails = patientDetails });
        }

        //
        // POST: /PatientCare/Create
        [HttpPost]
        public ActionResult Create(Patient patient)
        {
            var location = SessionHelper.GetLocation(HttpContext);
            if (ModelState.IsValid && !string.IsNullOrEmpty(location))
            {
                
                patient.CreatedDate = DateTime.Now;
                patient.Location = location;

                _db.Patients.Add(patient);
                _db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        //
        // GET: /PatientCare/Edit/5
        public ActionResult Edit(int patientId = 0)
        {
            var patient = _db.Patients.Find(patientId);
            var patientDetails = _db.PatientDetails.Include("InitialAssesment")
                                                   .Include("DetailedAssesment.Readings")
                                                   .Include("Investigation")
                                                   .Include("Treatment.LifeLines")
                                                   .Include("Treatment.TreatmentDetails")
                                                   .Include("Synopsis")
                                                .SingleOrDefault(p => p.PatientId == patientId)
                                ?? PatientHelper.GetNewPatientDetails(patientId);

            patientDetails.EnteredBy = User.Identity.Name;
            return View(new PatientDetailsViewModel() { Patient = patient, PatientDetails = patientDetails });
        }

        //
        // POST: /PatientCare/Edit/5
        [HttpPost]
        public ActionResult Edit(PatientDetailsViewModel pViewModel)
        {
            //var errors = ModelState.Values.Where(k => k.Errors.Count > 0);

            if (ModelState.IsValid)
            {
                var patient = _db.Patients.Find(pViewModel.Patient.PatientId);
                var patientDetails = _db.PatientDetails.Include("InitialAssesment")
                                                .Include("DetailedAssesment.Readings")
                                                .Include("Investigation")
                                                .Include("Treatment.LifeLines")
                                                .Include("Treatment.TreatmentDetails")
                                                .Include("Synopsis")
                                                .SingleOrDefault(p => p.PatientId == pViewModel.PatientDetails.PatientId);

                if (patientDetails == null)
                {
                    //Basic info
                    _db.Entry(patient).CurrentValues.SetValues(pViewModel.Patient);
                    GetInvestigationImages(pViewModel.PatientDetails.Investigation);
                    //Details
                    _db.PatientDetails.Add(pViewModel.PatientDetails);
                    //Photos
 
                }
                else
                {
                    //Basic info
                    _db.Entry(patient).CurrentValues.SetValues(pViewModel.Patient);
                    //Detailed info
                    _db.Entry(patientDetails).CurrentValues.SetValues(pViewModel.PatientDetails);
                    //Initial Assesment
                    _db.Entry(patientDetails.InitialAssesment)
                       .CurrentValues.SetValues(pViewModel.PatientDetails.InitialAssesment);
                    //Detailed Assesment
                    _db.Entry(patientDetails.DetailedAssesment)
                       .CurrentValues.SetValues(pViewModel.PatientDetails.DetailedAssesment);
                    //Readings
                    patientDetails.DetailedAssesment.Readings.ForEach(r => _db.Entry(r).CurrentValues.SetValues(
                        pViewModel.PatientDetails.DetailedAssesment.Readings.First(pdr => pdr.ID == r.ID)));
                    //Treatment
                    _db.Entry(patientDetails.Treatment).CurrentValues.SetValues(pViewModel.PatientDetails.Treatment);
                    //LifeLines
                    patientDetails.Treatment.LifeLines.ForEach(l => _db.Entry(l).CurrentValues.SetValues(
                        pViewModel.PatientDetails.Treatment.LifeLines.First(pdl => pdl.ID == l.ID)));
                    //Treatment Details
                    patientDetails.Treatment.TreatmentDetails.ForEach(td => _db.Entry(td).CurrentValues.SetValues(
                        pViewModel.PatientDetails.Treatment.TreatmentDetails.First(pdtd => pdtd.ID == td.ID)));
                    //Synopsis
                    _db.Entry(patientDetails.Synopsis).CurrentValues.SetValues(pViewModel.PatientDetails.Synopsis);
                    //Investigation
                    _db.Entry(patientDetails.Investigation)
                       .CurrentValues.SetValues(pViewModel.PatientDetails.Investigation);
                    GetInvestigationImages(patientDetails.Investigation);
                }
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(pViewModel);
        }

        //
        // GET: /Patient/Print/5
        public ActionResult Print(int patientId = 0)
        {
            var patient = _db.Patients.Find(patientId);
            if (patient == null)
            {
                return HttpNotFound();
            }
            return View(patient);
        }

        //
        // GET: /PatientCare/Delete/5
        public ActionResult Delete(int patientId = 0)
        {
            Patient patientcarerecord = _db.Patients.Find(patientId);
            if (patientcarerecord == null)
            {
                return HttpNotFound();
            }
            return View(patientcarerecord);
        }

        //
        // POST: /PatientCare/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int patientId)
        {
            Patient patientcarerecord = _db.Patients.Find(patientId);
            _db.Patients.Remove(patientcarerecord);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        //Get Image
        public ActionResult GetInvesigationImage(string imageKey, int patientId = 0)
        {
            var imgData = new byte[0];
            var details = _db.PatientDetails.Include("Investigation").SingleOrDefault(p => p.PatientId == patientId);
            if (details != null)
            {
                switch (imageKey)
                {
                    case "Photos1":
                        imgData = details.Investigation.Photos1;
                        break;

                }
            }
            if (imgData != null)
                return File(imgData, System.Net.Mime.MediaTypeNames.Image.Jpeg);
            else
                return new EmptyResult();
        }

        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }

        private void GetInvestigationImages(Investigation invObj)
        {
            if (Request.Files.Count <= 0) return;

            var photos = _db.Entry(invObj).Entity;
            if (Request.Files["Photos1"] != null) photos.Photos1 = PatientHelper.GetImage(HttpContext, "Photos1");
            if (Request.Files["Photos2"] != null) photos.Photos2 = PatientHelper.GetImage(HttpContext, "Photos2");
        }
    }
}